import { getItem, setItem, removeItem } from '@/utils/storage' //getItem和setItem是封装的操作localStorage的方法
import { AesEncryption } from '@/utils/encrypt'
import { toRaw } from 'vue'
export const TOKEN = 'MeClan-TOKEN'
const COLLAPSE = 'MeClan-COLLAPSE'
export default {
    namespaced: true,
    state: {
        title: 'Me Clan',
        authorization: getItem(TOKEN),
        device: 'desktop',
    },
    mutations: {
        setToken(state, data) {
            state.authorization = data
            // 保存到localStorage
            setItem(TOKEN, data)
        },
        clearToken(state) {
            state.authorization = ''

            removeItem(TOKEN)
        },
        setDevice(state, device) {
            state.device = device
        },
    },
    actions: {
        clearToken({ commit }) {
            // 清除token
            commit('clearToken')
            // 清除用户信息
            commit('users/clearUserinfo', '', { root: true })
        },
        setScreenCode({ commit, state }, password) {
            const authorization = toRaw(state.authorization)

            if (!password) {
                try {
                    delete authorization.screenCode
                } catch (err) {
                    console.log(err)
                }
                commit('setToken', authorization)

                return
            }

            // 对密码加密
            const screenCode = new AesEncryption().encryptByAES(password)

            commit('setToken', {
                ...authorization,
                screenCode,
            })
        },
    }
}